package hot;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author lakersUp
 * @Classname   三数之和
 * @Description     排序加三指针
 * @Date 2022/3/8 15:42
 * @Version 1.0
 */
public class Hot15threeSum {
    public List<List<Integer>> threeSum(int[] nums) {
        if(nums==null || nums.length==0){
            return new ArrayList<>();
        }
        int n=nums.length;
        List<List<Integer>> res=new ArrayList<>();
        Arrays.sort(nums);
        for(int first=0;first<n;first++){
            if(nums[first]>0){
                continue;
            }
            if(first>0 && nums[first]==nums[first-1]){
                continue;
            }
            int target=-nums[first];
            int third=n-1;
            for(int second=first+1;second<n;second++) {

                if(second>first+1 && nums[second]==nums[second-1]){
                    continue;
                }
                // second<third 去重
                while (second<third && nums[second] + nums[third] > target){
                    third--;
                }
                if(second==third){
                    break;
                }

                if (nums[second] + nums[third] == target) {
                    List<Integer> list = new ArrayList<>();
                    list.add(nums[first]);
                    list.add(nums[second]);
                    list.add(nums[third]);
                    res.add(new ArrayList<>(list));
                }
            }
        }
        return res;
    }
}
